import { createRouter, createWebHistory  } from "vue-router"

import { cookie } from "@/utils/cookie"

import routes from "./routes"

import { i18n, useLocales, SUPPORT_LOCALES, loadLocaleMessages, setI18nLanguage } from '@/i18n'

import { useUserStore } from "@/store/user"

const registerList = ['/login', '/register']

const basicPage = ['/about', '/index', '/hot', '/news', '/']

// 路由白名单  例如 login 登录页面
const whileList = new Set([...basicPage])

const initSetup = (to: any, token: any, next: any) => {
  switch(true){
    case (whileList.has(to.path)): return next()
    case (registerList.includes(to.path)): 
      if(![null, undefined, 'undefined'].includes(token)) return next('/home')
    return next()
    case ([null, undefined, 'undefined'].includes(token)): return next('/login')
    default: return registerList.includes(to.path) ?  next('/home') : next()
  }
} 

const setupI18n = async (to: any, init: any) => {
  try{
    const store = useUserStore()
    
     // 读取本地存储  存储的语言和默认值不相同， 用存储值
     if(i18n.global.locale !== store.lang) { useLocales(store.lang as any) }

     // use locale if paramsLocale is not in SUPPORT_LOCALES
     if (!SUPPORT_LOCALES.includes(to.params.locale)) return init()

     // load locale messages
     if (!i18n.global.availableLocales.includes(to.params.locale)) { 
       await loadLocaleMessages(i18n, to.params.locale) 
     }

     // set i18n language
     setI18nLanguage(i18n, to.params.locale)
  } catch(err: any){
     throw new Error(err)
  }
}

const router = createRouter({
  history: createWebHistory(),
  routes,
})


router.beforeEach(async (to, from, next) => {
  try {
    const token = cookie.getItem('accessToken')
    
    await setupI18n(to, initSetup(to, token, next))

    return initSetup(to, token, next)
    
  } catch(err: any){
    throw new Error(err)
  } 
})

export default router
